﻿<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <title>上传文件</title>
</head>
<body>
    选择文件上传：<input id="inputFile" type="file" />
    <br />
    <img id="result" src="/no-image.jpeg" alt="暂无图片" />

    <script src="./signalr.js"></script>
    <script>
        function resetImgUrl(imgObj, imgSrc, maxErrorNum) {
            if (maxErrorNum > 0) {
                imgObj.onerror = function () {
                    reSetImgUrl(imgObj, imgSrc, maxErrorNum - 1);
                };
                setTimeout(function () {
                    imgObj.src = imgSrc;
                }, 500);
            } else {
                imgObj.onerror = null;
                imgObj.src = "no-image.jpeg";
            }
        }

        function getObjectURL(file) {
            var url = null;
            if (window.createObjectURL != undefined) {
                url = window.createObjectURL(file)
            } else if (window.URL != undefined) {
                url = window.URL.createObjectURL(file)
            } else if (window.webkitURL != undefined) {
                url = window.webkitURL.createObjectURL(file)
            }
            return url
        };

        //const __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
        //    return new (P || (P = Promise))(function (resolve, reject) {
        //        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        //        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        //        function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
        //        step((generator = generator.apply(thisArg, _arguments || [])).next());
        //    });
        //};

        const __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
            //debugger
            //console.log(generator);
            return new (P || (P = Promise))(function (resolve, reject) {
                function fulfilled(value) {
                    try {
                        step(generator.next(value));
                    } catch (e) {
                        reject(e);
                    }
                }

                function rejected(value) {
                    try {
                        step(generator["throw"](value));
                    } catch (e) {
                        reject(e);
                    }
                }

                function step(result) {
                    if (result instanceof Promise) {
                        result
                            .then(r => {
                                //debugger
                                r.done ? resolve(r.value) : new P(function (resolve) {
                                    resolve(r.value);
                                }).then(fulfilled, rejected);
                            })
                            .catch(e => reject(e))
                    }
                    else {
                        //debugger
                        result.done ? resolve(result.value) : new P(function (resolve) {
                            resolve(result.value);
                        }).then(fulfilled, rejected);
                    }
                }

                //debugger
                //generator = generator.apply(thisArg, _arguments || []);
                //n = generator.next()
                //step(n);
                step((generator = generator.apply(thisArg, _arguments || [])).next());
            });
        };

        // 链接到自己的hub 初始化 路由：/streaming 被路由节点捕获
        let connection = new signalR.HubConnectionBuilder()
            .withUrl("/streaming")
            .build();
        connection.start().then(() => {
            console.log("已建立链接");
        });

        let resultImg = document.querySelector('#result');
        let inputFile = document.querySelector('#inputFile');

        function blobToDataURI(blob) {
            return new Promise((resolve, reject) => {
                var reader = new FileReader();
                reader.readAsDataURL(blob);
                reader.onload = function (e) {
                    resolve(e.target.result);
                }
            });
        }

        function getBase64(file) {
            return new Promise((resolve, reject) => {
                let reader = new FileReader();
                let imgResult = "";
                reader.readAsDataURL(file);
                reader.onload = function () {
                    imgResult = reader.result;
                };
                reader.onerror = function (error) {
                    reject(error);
                };
                reader.onloadend = function () {
                    resolve(imgResult);
                };
            });
        }

        // #region
        //inputFile.addEventListener('change', async event => {
        //    if (event.target.files.length) {
        //        let file = event.target.files[0];
        //        console.log(file);
        //        console.log({ name: file.name, size: file.size, type: file.type });

        //        let shardSize = 1 * 1024 * 1024; // 分片大小
        //        let shardCount = Math.ceil(file.size / shardSize); // 总分片数

        //        for (let i = 0; i < shardCount; i++) {
        //            let start = i * shardSize; // 分片开始位置
        //            let end = start + shardSize; // 分片结束位置
        //            let packet = file.slice(start, end);  // 将文件进行切片

        //            //console.log(packet);
        //            debugger

        //            let base64Data = await blobToDataURI(packet);
        //            console.log(base64Data);
        //            let base64Image = base64Data.split(';base64,')[1];
        //            console.log(base64Image);
        //        }
        //    }
        //    //console.log(event.target.files.length);
        //});
        // #endregion

        inputFile.addEventListener('change', async event => {
            if (event.target.files.length) {
                let file = event.target.files[0];
                let base64Images = [];
                //debugger

                const fileType = file.type.substring(
                    file.type.lastIndexOf("/") + 1,
                    file.type.length
                );
                let type =
                    fileType == "jpg" ||
                    fileType == "jpeg" ||
                    fileType == "png" ||
                    fileType == "JPG" ||
                    fileType == "JPEG";
                console.log("type", type);
                if (!type) {
                    console.log("上传图片只能是jpg 、 jpeg 、 png 、 JPG 、 JPEG格式!");
                    return;
                }

                // 发送内容
                let shardSize = 1024; // 分片大小
                let shardCount = Math.ceil(file.size / shardSize); // 总分片数

                for (let i = 0; i < shardCount; i++) {
                    let start = i * shardSize; // 分片开始位置
                    let end = start + shardSize; // 分片结束位置
                    let packet = file.slice(start, end);  // 将文件进行切片

                    //debugger
                    let base64Data = await getBase64(packet);
                    let base64Image = base64Data.split(';base64,')[1];
                    base64Images.push(base64Image);
                }
                //console.log(base64Images)

                //debugger
                __awaiter(this, void 0, void 0, function* () {
                    const subject = new signalR.Subject();
                    try {
                        yield connection.send('UploadImage', subject);

                        // 发送文件名
                        let fileName = file.name;
                        subject.next(fileName);
                        //debugger

                        for (let i = 0; i < base64Images.length; i++) {
                            let base64Image = base64Images[i];
                            subject.next(base64Image);
                        }
                    } catch (e) {
                        console.error(e);
                        resultImg.src = '/no-image.jpeg';
                        return;
                    }
                    finally {
                        subject.complete();
                    }
                });

                //setTimeout(() => {
                //    resultImg.src = `/upload/${file.name}`;
                //}, 1000);

                //resetImgUrl(resultImg, `/upload/${file.name}`, 10);

                resultImg.src = getObjectURL(file);
            }

            //event.preventDefault();
        });
    </script>
</body>
</html>

<!-- http://www.manongjc.com/detail/24-civwrgnuqscbpsp.html -->
<!-- https://blog.csdn.net/qq_40190624/article/details/125309074 -->
<!-- https://pixabay.com/zh/photos/ -->
<!-- http://t.zoukankan.com/lalalagq-p-9959786.html -->
<!-- https://blog.csdn.net/libin_1/article/details/50433863 -->
